package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.SearchItemAdapter;
import com.shaoshaohuo.app.adapter.Search_Exact_Adapter;
import com.shaoshaohuo.app.constant.ShareKey;
import com.shaoshaohuo.app.entity.HotSearchEntity;
import com.shaoshaohuo.app.entity.Search_Exact_Entity;
import com.shaoshaohuo.app.entity.Search_Item_Entity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.RequestParam;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.ui.fragment.MyInfoFragment;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.view.FlowLayout;
import com.shaoshaohuo.app.view.TopbarView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class Search_Activity extends AppCompatActivity implements View.OnClickListener, TextWatcher, AdapterView.OnItemClickListener {
    private Handler handler_item = new Handler();
    private Handler handler_exect = new Handler();
    /**
     * tobar
     */
    private TextView right_textView_Button;
    private TopbarView topbarView;
    private ImageView imageview_topbar_left_backImage;
    /**
     * 热门 搜索
     */
    private FlowLayout search_flowLayout;
    //    private String[] hot_sort = new String[]{"西瓜", "葡萄", "哈蜜瓜", "红提葡萄", "芒果", "柠檬", "火龙果", "猕猴桃"};
    //    private String[] hot_sort = new String[]{"西瓜", "葡萄", "哈蜜瓜", "红提葡萄", "芒果", "柠檬", "火龙果", "猕猴桃"};
    private EditText search_toobar_input;
    private LinearLayout search_hot_linearLayout;
    private ListView search_item_listView;
    private List<Search_Item_Entity.DataBean> search_item_data;
    private SearchItemAdapter search_item_adapter;
    private String search_word = "";//记录输入的内容
    private TextView hot_textView;
    /**
     * 精确搜索
     */
    private ListView search_exact_listView;
    private Search_Exact_Adapter search_exact_adapter;
    private List<Search_Exact_Entity.DataBean> search_exect_data;

    /**
     * 浏览历史
     */
    private ArrayList<String> histroy_data;
    private FlowLayout search_history;
    private SharedPreferencesHelper search_helper;
    private ImageView search_history_delete;
    private RelativeLayout search_history_look;
    private boolean flag = false;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_);
        ininView();
        requestHotData();
        initListener();
        bindAdapter();
    }

    private void setSearchHistory() {
        Log.e("搜索历史", histroy_data.size() + "");
        requestData(histroy_data, search_history);
    }

    private void requestHotData() {
        ShopHttpConfig.hotSearch(getApplicationContext(), new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                Log.e("失败", "失败");
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                Log.e("成功", "成功");
                final HotSearchEntity hotentity = (HotSearchEntity) o;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List<String> data = hotentity.getData();
                        requestData(data, search_flowLayout);
                    }
                });
            }
        }, HotSearchEntity.class);
    }

    private void bindAdapter() {
        search_item_listView.setAdapter(search_item_adapter);
        search_exact_listView.setAdapter(search_exact_adapter);
    }

    private void initListener() {
        search_history_delete.setOnClickListener(this);
        right_textView_Button.setOnClickListener(this);
        search_toobar_input.addTextChangedListener(this);
        search_item_listView.setOnItemClickListener(this);
        search_exact_listView.setOnItemClickListener(this);
        search_toobar_input.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.e("nihao nihao ", search_toobar_input.getText().toString().trim());
//                search_toobar_input.setText("");
                search_toobar_input.setHint("");
                search_toobar_input.setCursorVisible(true);
//                search_toobar_input.setCompoundDrawables(null, null, null, null);
                Log.e("换图片", "左侧消失，右侧显现");
//                search_toobar_input.requestFocus();
//                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                im.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                return false;
            }
        });
//        search_toobar_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//
//                return true;
//            }
//        });
        imageview_topbar_left_backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        search_flowLayout.setOnClickListener(this);
    }
    private void requestData(List<String> data, FlowLayout flowLayout) {
        if (data != null || data.size() > 0) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(22, 14, 22, 14);
            for (int i = 0; i < data.size(); i++) {
                hot_textView = new TextView(this);
                Drawable d = getResources().getDrawable(R.drawable.search_hot);
                hot_textView.setLayoutParams(params);
                hot_textView.setText(data.get(i));
                hot_textView.setPadding(12, 8, 12, 8);
                hot_textView.setBackground(d);
                hot_textView.setGravity(Gravity.CENTER);
                hot_textView.setTextSize(14);
                hot_textView.setTextColor(getResources().getColor(R.color.color_323232));
                flowLayout.addView(hot_textView);
                hot_textView.setTag(data.get(i));
                hot_textView.setId(1);
                Log.e("TAG", "requestData: zzzzzzzzzzzz");
                hot_textView.setOnClickListener(this);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_message:
                String input_subStance = search_toobar_input.getText().toString().trim();
                if (input_subStance == null || input_subStance.isEmpty() || input_subStance.length() <= 0) {
                    Toast.makeText(this, "输入内容为空,请重新输入", Toast.LENGTH_SHORT).show();
                } else {
                    search_item_data.clear();
                    search_item_adapter.setNotify(search_item_data);
                    search_item_listView.setVisibility(View.GONE);
                    reqestExectData(input_subStance);
                }
                addHistorySharedPreferencesHelper();
                break;
            case 1:
                String string_hot = ((TextView) v).getText().toString();
//                Toast.makeText(getApplication(), string_hot, Toast.LENGTH_SHORT).show();
                search_toobar_input.setCursorVisible(true);
                search_toobar_input.setHint("");
                search_toobar_input.setText(string_hot);
                search_toobar_input.setSelection(string_hot.length());
                break;
            case R.id.search_history_delete:
                histroy_data.clear();
                search_history.removeAllViews();
                search_history_look.setVisibility(View.GONE);
                search_helper.setArrayString(getApplicationContext(), SharedPreferencesHelper.Field.SEARCH_HISTORY, histroy_data);
                break;
        }
    }

    private void ininView() {
        /**
         * 顶部tobar
         * */
        topbarView = (TopbarView) findViewById(R.id.search_toBar);
        LinearLayout layout_topbar_left = (LinearLayout) findViewById(R.id.layout_topbar_left);
        layout_topbar_left.setVisibility(View.VISIBLE);
        TextView textView = (TextView) findViewById(R.id.textView_tobar_left);
        textView.setVisibility(View.GONE);
        imageview_topbar_left_backImage = (ImageView) findViewById(R.id.imageview_topbar_left_backImage);
        imageview_topbar_left_backImage.setImageResource(R.mipmap.return_key);
        imageview_topbar_left_backImage.setVisibility(View.VISIBLE);


        right_textView_Button = (TextView) findViewById(R.id.textview_message);
        right_textView_Button.setText("搜索");
        right_textView_Button.setVisibility(View.VISIBLE);
        ImageView right_ImageView = (ImageView) findViewById(R.id.imageview_message);
        right_ImageView.setVisibility(View.GONE);
        search_toobar_input = (EditText) findViewById(R.id.toobar_input);
        search_toobar_input.setTextSize(13);
//        search_toobar_input.setSelection(5);
        search_toobar_input.setTextColor(getResources().getColor(R.color.color_646464));
        search_toobar_input.setVisibility(View.VISIBLE);
        TextView toolbar_topname = (TextView) findViewById(R.id.toolbar_topname);
        toolbar_topname.setVisibility(View.GONE);
        /**
         * 热门搜索
         * */
        search_flowLayout = (FlowLayout) findViewById(R.id.search_flowLayout);
        search_item_data = new ArrayList<>();
        search_item_adapter = new SearchItemAdapter(this, search_item_data);
        search_hot_linearLayout = (LinearLayout) findViewById(R.id.search_hot_linearLayout);
        search_item_listView = (ListView) findViewById(R.id.search_item_listView);
//        search_item_listView.setVisibility(View.GONE);
        /**
         * 搜索结果
         * */
        search_exact_listView = (ListView) findViewById(R.id.search_exact_listView);
        search_exact_adapter = new Search_Exact_Adapter(this, search_exect_data);
        search_exect_data = new ArrayList<>();
//        search_exact_listView.setVisibility(View.GONE);
        /**
         * 搜搜历史
         * */
        search_history = (FlowLayout) findViewById(R.id.search_history);
        histroy_data = new ArrayList<>();
        search_helper = new SharedPreferencesHelper();
        histroy_data = SharedPreferencesHelper.getArrayString(getApplicationContext(), SharedPreferencesHelper.Field.SEARCH_HISTORY, "");
        search_history_delete = (ImageView) findViewById(R.id.search_history_delete);
        search_history_look = (RelativeLayout) findViewById(R.id.search_history_look);
        if (histroy_data == null || histroy_data.size() == 0) {
            search_history_look.setVisibility(View.GONE);
        } else {
            search_history_look.setVisibility(View.VISIBLE);
            search_history.setVisibility(View.VISIBLE);
            setSearchHistory();
        }

    }


    private void reqestExectData(String subStances) {
        Map<String, String> map_key = new HashMap<>();
        map_key.put("key", subStances);
        Map<String, String> map_head = RequestParam.getHeaderParams();
        Okhttputils.Instanse(this).postFromBody(map_head, HttpConfig.BASE_HOST_URL + HttpConfig.SubUrl.SEARCH_EXECT, map_key, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                if (code == 211) {
                    handler_exect.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "未找到商品，请选择其他商品", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                Search_Exact_Entity search_exact_entity = (Search_Exact_Entity) o;
                search_exect_data = search_exact_entity.getData();
                handler_exect.post(new Runnable() {
                    @Override
                    public void run() {
                        search_hot_linearLayout.setVisibility(View.GONE);
                        search_exact_listView.setVisibility(View.VISIBLE);
                        search_exact_adapter.freshenAdapter(search_exect_data);
                    }
                });
//                }
            }
        }, Search_Exact_Entity.class);

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.e(s.toString(), search_toobar_input.getText().toString().trim());
//        Toast.makeText(this, s.toString(), Toast.LENGTH_SHORT).show();
        String mString = s.toString();
        if (mString == null || mString.isEmpty() || mString.equals("") || mString.length() <= 0) {
            search_item_data.clear();
            search_exect_data.clear();
            search_item_listView.setVisibility(View.GONE);
            search_hot_linearLayout.setVisibility(View.VISIBLE);
            search_exact_listView.setVisibility(View.GONE);
        } else {
            if (search_word.equals(mString)) {
                Log.e("输入状态", "输入没变化");
            } else {
//                search_toobar_input.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.chahao), null);
                search_exact_listView.setVisibility(View.GONE);
                //访问数据
                requestItemData(mString);
            }
        }
        search_word = mString;
    }

    private void requestItemData(final String s) {
        Map<String, String> map_key = new HashMap<>();
        map_key.put("key", s);
        Map<String, String> map = RequestParam.getHeaderParams();
        Okhttputils.Instanse(this).postFromBody(map, HttpConfig.BASE_HOST_URL + HttpConfig.SubUrl.SEARCH_ITEM, map_key, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {
                if (code == 211) {
                    handler_item.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "未找到商品，请选择其他商品", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                Search_Item_Entity search_item = (Search_Item_Entity) o;
                search_item_data = search_item.getData();
                Log.e("search_item.getCode()", search_item.getCode() + "");
//                if (search_item.getCode() == 211) {
//                    Toast.makeText(getApplicationContext(), "未找到商品，请选择其他商品", Toast.LENGTH_SHORT).show();
//                } else {
                handler_item.post(new Runnable() {
                    @Override
                    public void run() {
                        search_hot_linearLayout.setVisibility(View.GONE);
                        search_item_listView.setVisibility(View.VISIBLE);
                        search_item_adapter.setNotify(search_item_data);

                    }
                });
            }
        }, Search_Item_Entity.class);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.search_item_listView:
                search_item_listView.setVisibility(View.GONE);
                search_exact_listView.setVisibility(View.VISIBLE);
                String name = search_item_data.get(position).getName();
                String level = search_item_data.get(position).getLevel();
                Log.e(name + "=======" + level, name + "===" + level);
                requestColumnItemData(name, level);
                addHistorySharedPreferencesHelper();
                break;
            case R.id.search_exact_listView:
                String catid = search_exect_data.get(position).getCatid();
                Intent intent = new Intent(this, NewDetailsActivity.class);
                intent.putExtra(ShareKey.CATID, catid);
                intent.putExtra("imgurl", search_exect_data.get(position).getImg());
                startActivity(intent);
                break;
        }
    }

    private void addHistorySharedPreferencesHelper() {
        String trim = search_toobar_input.getText().toString().trim();
        if (histroy_data.size() >= 10) {
            for (int i = 0; i < histroy_data.size(); i++) {
                if (trim.equals(histroy_data.get(i))) {
                    histroy_data.remove(i);
                    flag = true;
                }
            }
            if (!flag) {
                histroy_data.remove(0);
                histroy_data.add(search_toobar_input.getText().toString().trim());
            }
            if (flag) {
                histroy_data.add(search_toobar_input.getText().toString().trim());
                flag = false;
            }

            Log.e("TAG", "addHistorySharedPreferencesHelper: =====");
        } else if (histroy_data.size() >= 0 && histroy_data.size() < 10) {
            for (int i = 0; i < histroy_data.size(); i++) {
                if (trim.equals(histroy_data.get(i))) {
                    histroy_data.remove(i);
                    Log.e("TAG", "addHistorySharedPreferencesHelper:" + i);
                    flag = true;
                }
            }
            if (!flag) {
                histroy_data.add(search_toobar_input.getText().toString().trim());
            }
            if (flag) {
                Log.e("TAG", "addHistory" + histroy_data.size());
                histroy_data.add(search_toobar_input.getText().toString().trim());
                for (int i = 0; i < histroy_data.size(); i++) {
                    Log.e("TAG", "addHistorySharedPreferencesHelper: " + histroy_data.get(i));
                }
                flag = false;
            }

        }
        Log.e("添加历史数据", histroy_data.size() + "");
        search_helper.setArrayString(getApplicationContext(), SharedPreferencesHelper.Field.SEARCH_HISTORY, histroy_data);
    }

    private void requestColumnItemData(String trim, String name) {
        Map<String, String> map_key = new HashMap<>();
        map_key.put("key", trim);
        map_key.put("level", name);
        Map<String, String> map_header = RequestParam.getHeaderParams();
        Okhttputils.Instanse(this).postFromBody(map_header, HttpConfig.BASE_HOST_URL + HttpConfig.SubUrl.SEARCH_EXECT, map_key, new Okhttputils.OkutListener() {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                search_exect_data.clear();
                Search_Exact_Entity search_exect_entity = (Search_Exact_Entity) o;
                search_exect_data = search_exect_entity.getData();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        search_exact_adapter.freshenAdapter(search_exect_data);
                    }
                });
            }
        }, Search_Exact_Entity.class);
    }
}
